package sc.digital.human;

import com.google.gson.Gson;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Token {
    private static final Logger logger = LoggerFactory.getLogger(Token.class);
    private final OkHttpClient httpClient = new OkHttpClient.Builder().build();
    private final Gson gson = new Gson();
    private Credentials credentials = new Credentials();

    public Token() {
    }

    /**
     * 刷新 Token
     *
     * @param callback 回调
     */
    public void refresh(Callback callback) {
        this.refresh(callback, Config.APP_KEY, Config.SECRET_KEY);
    }

    /**
     * 刷新 Token
     *
     * @param callback  回调
     * @param appKey    AK
     * @param secretKey SK
     */
    public void refresh(Callback callback, String appKey, String secretKey) {
        if (this.credentials != null
                && this.credentials.access_token != null
                && !this.credentials.access_token.isEmpty()
                && this.credentials.expires_in > System.currentTimeMillis()) {
            callback.token(this.credentials);
        } else {
            this.httpClient.newCall(new Request.Builder()
                    .url(String.format(Config.TOKEN_URL, appKey, secretKey))
                    .build()).enqueue(new okhttp3.Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (logger.isInfoEnabled()) {
                        logger.info("鉴权认证：{}", response);
                    }
                    if (!response.isSuccessful() || response.body() == null) {
                        callback.token(null);
                    } else {
                        String json = response.body().string();
                        if (logger.isInfoEnabled()) {
                            logger.info("鉴权认证：{}", json);
                        }
                        credentials = gson.fromJson(json, Credentials.class);
                        credentials.expires_in = System.currentTimeMillis() + credentials.expires_in * 1000;
                        callback.token(credentials);
                    }
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    if (logger.isErrorEnabled()) {
                        logger.error("鉴权认证：{}", e, e);
                    }
                    callback.token(null);
                }
            });
        }
    }

    interface Callback {
        /**
         * 获取 Token
         *
         * @param credentials Token
         */
        void token(Credentials credentials);
    }

    static class Credentials {
        public String access_token;
        public long expires_in;
    }
}
